import type { FormInstance } from 'element-plus'
import type { SystemDictOptionsType, SystemDictDataItemType } from './typings'
import { defineComponent, ref, reactive } from 'vue'
import { useStore } from 'vuex'
import {
  ElDialog,
  ElForm,
  ElRow,
  ElCol,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElButton,
  ElSelect,
  ElOption,
  ElMessage,
  ElIcon
} from 'element-plus'
import { CirclePlus, CircleClose } from '@element-plus/icons-vue'
import { GUTTER, SPAN_STYLE_DOUBLE } from '~/utils/const'
import { handleTrim } from '~/utils/util'
import type { parentDictEnum } from '~/store/system/typings'
import useVuexGetters from '~/hooks/useVuexGetters'
import styles from '~/pages/system/index.module.scss'

export default defineComponent({
  name: 'SystemDictOptions',
  props: ['visible', 'type', 'record'],
  emits: ['cancel'],
  setup(props: SystemDictOptionsType, { emit }) {
    const store = useStore()
    const systemDictState = useVuexGetters('systemDict', ['parentDictSelectList', 'parentDictEnum'])

    const ruleFormRef = ref<FormInstance>()
    const codeDisabledRef = ref(false) // 字典编号
    const parentDictDisabledRef = ref(false) // 上级字典
    const title = { add: '新增', update: '编辑', read: '查看', addSon: '新增子项' }

    const optionsValidateForm = reactive<SystemDictDataItemType>(
      Object.assign(
        {
          code: '', // 字典编号
          dictValue: '', // 字典名称
          parentId: '', // 上级字典
          dictKey: undefined, // 字典键值
          sort: undefined, // 字典排序
          remark: '' // 字典备注
        },
        props.record
      )
    )

    // 新增子项 是否可填
    if (props.visible && props.type === 'addSon') {
      codeDisabledRef.value = true // 字典编号
      parentDictDisabledRef.value = true // 上级字典
      optionsValidateForm.dictValue = '' // 字典名称
      optionsValidateForm.parentId = optionsValidateForm.id
      optionsValidateForm.dictKey = undefined // 字典键值
      optionsValidateForm.sort = undefined // 字典排序
      optionsValidateForm.remark = '' // 字典备注
    }

    // 编辑 是否可填
    if (props.visible && props.type === 'update' && optionsValidateForm.parentId === '0') {
      parentDictDisabledRef.value = true // 上级字典
    }

    // 关闭弹框事件回调
    const handleCloseModal = () => {
      emit('cancel')
    }

    return () => {
      const { type, visible } = props
      // 提交表单
      const handleSubmitForm = () => {
        if (!ruleFormRef.value) return
        ruleFormRef.value.validate(async (valid) => {
          if (!valid) return
          if (type === 'addSon' && optionsValidateForm.id !== '') {
            delete optionsValidateForm.id
          }
          // 去输入的前后空格
          optionsValidateForm.code = handleTrim(optionsValidateForm.code ?? '')
          optionsValidateForm.dictValue = handleTrim(optionsValidateForm.dictValue ?? '')
          optionsValidateForm.remark = handleTrim(optionsValidateForm.remark ?? '')

          const params = { ...optionsValidateForm }
          const res = await store.dispatch('systemDict/PostSystemDictSubmit', params) // 字典的 新增与编辑 为同一接口
          if (res?.code === 200) {
            ElMessage({ type: 'success', message: '操作成功' })
            handleCloseModal()
          } else {
            ElMessage({ type: 'error', message: res?.msg ?? '操作失败' })
          }
        })
      }

      return (
        <ElDialog
          title={(title[type] as string) || '查看'}
          modelValue={visible}
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={handleCloseModal}
          v-slots={
            type !== 'read' && {
              footer: () => (
                <>
                  <ElButton type="primary" onClick={handleSubmitForm}>
                    <ElIcon>
                      <CirclePlus />
                    </ElIcon>
                    &nbsp; {type === 'update' ? '修改' : '保存'}
                  </ElButton>
                  <ElButton onClick={handleCloseModal}>
                    <ElIcon>
                      <CircleClose />
                    </ElIcon>
                    取消
                  </ElButton>
                </>
              )
            }
          }
        >
          <div class={styles['systemPostOption-form']}>
            <ElForm label-width="100px" ref={ruleFormRef} model={optionsValidateForm}>
              <ElRow>
                <ElCol>
                  <ElFormItem
                    prop="code"
                    label="字典编号"
                    rules={[{ required: true, message: '请输入 字典编号', trigger: 'change' }]}
                  >
                    {type === 'read' ? (
                      optionsValidateForm.code
                    ) : (
                      <ElInput
                        v-model={optionsValidateForm.code}
                        disabled={codeDisabledRef.value}
                        placeholder="请输入 字典编号"
                      />
                    )}
                  </ElFormItem>
                </ElCol>
              </ElRow>
              <ElRow gutter={GUTTER}>
                <ElCol {...SPAN_STYLE_DOUBLE}>
                  <ElFormItem
                    prop="dictValue"
                    label="字典名称"
                    rules={[{ required: true, message: '请输入 字典名称', trigger: 'change' }]}
                  >
                    {type === 'read' ? (
                      optionsValidateForm.dictValue
                    ) : (
                      <ElInput
                        v-model={optionsValidateForm.dictValue}
                        placeholder="请输入 字典名称"
                      />
                    )}
                  </ElFormItem>
                </ElCol>
                <ElCol {...SPAN_STYLE_DOUBLE}>
                  <ElFormItem prop="parentId" label="上级字典">
                    {type === 'read' ? (
                      systemDictState.parentDictEnum.value?.[optionsValidateForm.parentId!] ||
                      '顶级'
                    ) : (
                      <ElSelect
                        v-model={optionsValidateForm.parentId}
                        disabled={parentDictDisabledRef.value}
                        placeholder="请选择 或输入关键字"
                        filterable
                        clearable
                      >
                        {systemDictState.parentDictSelectList?.value?.map(
                          (item: parentDictEnum) => (
                            <ElOption key={item?.key} label={item?.title} value={item?.key} />
                          )
                        )}
                      </ElSelect>
                    )}
                  </ElFormItem>
                </ElCol>
                <ElCol {...SPAN_STYLE_DOUBLE}>
                  <ElFormItem
                    prop="dictKey"
                    label="字典键值"
                    rules={[{ required: true, message: '请输入 字典键值', trigger: 'change' }]}
                  >
                    {type === 'read' ? (
                      optionsValidateForm.dictKey
                    ) : (
                      <ElInputNumber
                        v-model={optionsValidateForm.dictKey}
                        min={0}
                        controls-position="right"
                        placeholder="请输入 字典键值"
                      />
                    )}
                  </ElFormItem>
                </ElCol>
                <ElCol {...SPAN_STYLE_DOUBLE}>
                  <ElFormItem
                    prop="sort"
                    label="字典排序"
                    rules={[{ required: true, message: '请输入 字典排序', trigger: 'change' }]}
                  >
                    {type === 'read' ? (
                      optionsValidateForm.sort
                    ) : (
                      <ElInputNumber
                        v-model={optionsValidateForm.sort}
                        min={0}
                        controls-position="right"
                        placeholder="请输入 字典排序"
                      />
                    )}
                  </ElFormItem>
                </ElCol>
              </ElRow>
              <ElRow>
                <ElCol>
                  <ElFormItem prop="remark" label="字典备注">
                    {type === 'read' ? (
                      optionsValidateForm.remark
                    ) : (
                      <ElInput v-model={optionsValidateForm.remark} placeholder="请输入 字典备注" />
                    )}
                  </ElFormItem>
                </ElCol>
              </ElRow>
            </ElForm>
          </div>
        </ElDialog>
      )
    }
  }
})
